<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="searchMap.name" placeholder="角色名" style="width: 200px" class="filter-item" @keyup.enter.native="fetchData" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="fetchData">
        搜索
      </el-button>
      <el-button v-waves class="filter-item create" type="primary" icon="el-icon-circle-plus-outline" @click="handleCreate()">
        添加角色
      </el-button>
    </div>
    <el-table v-loading="listLoading" border fit stripe highlight-current-row :data="list" style="width: 100%" height="500" max-height="500" size="small">
      <el-table-column sortable label="序号" prop="id" width="70" align="center">
        <template slot-scope="{ row }">
          <p>{{ row.id }}</p>
        </template>
      </el-table-column>
      <el-table-column label="角色名称" prop="name" width="120" align="center" />
      <el-table-column label="描述" prop="description" align="center" />
      <el-table-column label="描述" prop="description" align="center" />
      <el-table-column label="创建时间" prop="created" align="center" :formatter="paresTime" />
      <el-table-column label="创建人" align="center">
        <template slot-scope="{ row }">
          <el-tag type="success">{{ row.creator }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="200" align="center">
        <template slot-scope="{ row }">
          <el-switch v-model="row.status" style="display: block" :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用" @change="changeStatus(row)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="220">
        <template slot-scope="{ row, $index }">
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleUpdate(row)" />
          <el-button size="mini" type="warning" icon="el-icon-unlock" @click="handlePermissionUpdate(row)" />
          <el-button v-if="row.status != 'deleted'" size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(row, $index)" />
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-show="total > 0" :current-page="searchMap.page" background :page-sizes="[5, 10, 20]" :page-size="searchMap.limit" layout="sizes, total, prev, pager, next,jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    
    <!-- 添加/编辑角色对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="pojo" label-position="left" label-width="70px" style="width: 85%; margin-left: 50px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="pojo.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="描述" prop="description">
              <el-input v-model="pojo.description" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
    
    <!-- 权限管理抽屉 -->
    <el-drawer ref="permisionDrawer" title="角色权限管理" :visible.sync="drawer" :before-close="handleClose" :destroy-on-close="destroyOnClose" :append-to-body="flag" size="40%">
      <div class="drawer-container">
        <div class="context">
          <el-card class="box-card" shadow="hover">
            <el-row type="flex" justify="space-between">
              <el-col :span="11">
                角色名称 : <el-tag type="success">{{ pojo.name }}</el-tag>
              </el-col>
              <el-col :span="11">
                创建人 : <el-tag type="success">{{ pojo.creator }}</el-tag>
              </el-col>
            </el-row>
            <div class="text" style="float:right;" />
          </el-card>
          <el-tree 
            ref="permissionTree" 
            class="ptree" 
            highlight-current 
            :default-checked-keys="checked" 
            :data="menuTree" 
            show-checkbox 
            node-key="id" 
            :default-expanded-keys="[0]" 
            :props="treeProps" 
            @check="handleCheckChange" />
          <div class="drawer-footer">
            <el-row type="flex" justify="space-between">
              <el-col :span="11">
                <el-button class="el-btn" @click="cancelForm">取 消</el-button>
              </el-col>
              <el-col :span="11">
                <el-button class="el-btn" type="primary" :loading="loading" @click="updateRoleMenu">{{ loading ? '提交中 ...' : '更改权限' }}</el-button>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import role from '@/api/role'
import { getMenuTree, getRoleHasMenu } from '@/api/menu'
import moment from 'moment'

export default {
  data() {
    return {
      flag: true,
      destroyOnClose: true,
      checked: [],
      treeProps: {
        label: 'label',      // 使用 label 字段
        children: 'children' // 使用 children 字段
      },
      menuTree: null,
      loading: false,
      tree: null,
      drawer: false,
      list: null,
      total: 0,
      listLoading: true,
      dialogFormVisible: false,
      dialogStatus: '',
      searchMap: {
        page: 1,
        limit: 5,
        name: undefined
      },
      pojo: {
        id: undefined,
        name: '',
        description: '',
        description: '',
        creator: '',
        created: undefined,
        status: undefined
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      textMap: {
        update: '编辑角色',
        create: '添加角色'
      }
    }
  },
  created() {
    this.fetchData()

    // 加载所有权限树
    setTimeout(() => {
      getMenuTree().then(res => {
        this.menuTree = res.data
      })
    }, 2 * 1000)
  },
  methods: {
    fetchData() {
      this.listLoading = true
      role.search(this.searchMap).then((res) => {
        this.listLoading = false
        this.list = res.data
        this.total = res.count
      })
    },
    paresTime(row, col) {
      const data = row[col.property]
      if (data === undefined) {
        return ''
      }
      return moment(data).format('YYYY-MM-DD HH:mm:ss')
    },
    changeStatus(row) {
      this.resetPojo()
      this.pojo.id = row.id
      this.pojo.status = row.status
      role.updateStatus(this.pojo).then((res) => {
        this.$notify({
          title: '成功',
          message: '状态更新成功',
          type: 'success',
          duration: 3000
        })
      })
    },
    handleSizeChange(limit) {
      this.searchMap.limit = limit
      this.fetchData()
    },
    handleCurrentChange(page) {
      this.searchMap.page = page
      this.fetchData()
    },
    resetPojo() {
      this.pojo = {
        id: undefined,
        name: '',
        description: '',
        description: '',
        creator: '',
        created: undefined,
        status: undefined
      }
    },
    handleUpdate(row) {
      this.pojo = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCreate() {
      this.resetPojo()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    updateData() {
      role.update(this.pojo).then((res) => {
      role.update(this.pojo).then((res) => {
        if (res.code === 0) {
          this.$notify({
            title: '成功',
            message: '编辑成功',
            type: 'success',
            duration: 3000
          })
          this.fetchData()
          this.dialogFormVisible = false
        }
      })
    },
    createData() {
      role.save(this.pojo).then((res) => {
      role.save(this.pojo).then((res) => {
        if (res.code === 0) {
          this.$notify({
            title: '成功',
            message: '添加成功',
            type: 'success',
            duration: 3000
          })
          this.fetchData()
          this.dialogFormVisible = false
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('确定要删除这条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          role.delete(row.id).then((res) => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 3000
            })
            this.list.splice(index, 1)
            if (res.code === 0) {
              this.fetchData()
            }
          })
        })
        .catch(() => {
          this.$notify({
            title: '提示',
            message: '取消删除',
            type: 'info',
            duration: 3000
          })
        })
    },
    resetChecked() {
      this.checked = []
    },
    handlePermissionUpdate(row) {
      this.resetChecked()
      this.pojo = Object.assign({}, row)
      this.drawer = true
      
      getRoleHasMenu(row.id).then(res => {
        if (res.code === 0 && res.data) {
          // 从菜单对象数组中提取id字段
          this.checked = res.data.map(menu => menu.id)
          console.log('提取的菜单ID:', this.checked)
        }
      }).catch(error => {
        console.error('获取角色菜单失败:', error)
        this.$message.error('获取角色菜单失败')
      })
    },
    handleClose(done) {
      this.$confirm('确定要关闭吗？未保存的更改将会丢失。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done()
      }).catch(() => {})
    },
    cancelForm() {
      this.drawer = false
    },
    updateRoleMenu() {
      this.$confirm('您正在更改当前用户菜单权限，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 先定义 roleMenuPojo，再使用
        const roleMenuPojo = {
          id: this.pojo.id,
          menuIds: this.checked
        }
        
        role.updateRoleMenu(roleMenuPojo).then(res => {
          this.loading = false
          if (res.code === 0) {
            this.$notify({
              title: '成功',
              message: '权限修改成功',
              type: 'success',
              duration: 3000
            })
            this.drawer = false
          } else {
            this.$notify({
              title: '错误',
              message: res.msg || '权限修改失败',
              type: 'error',
              duration: 3000
            })
          }
        }).catch(error => {
          this.loading = false
          this.$notify({
            title: '错误',
            message: '权限修改失败',
            type: 'error',
            duration: 3000
          })
        })
      }).catch(() => {
        this.loading = false
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
      
      this.loading = true
    },
    handleCheckChange() {
      this.getCheckedKeys()
    },
    getCheckedKeys() {
      this.checked = this.$refs.permissionTree.getCheckedKeys()
    }
  }
}
</script>

<style scoped>
.filter-item {
  margin-bottom: 10px;
  margin-right: 10px;
}

.app-container {
  padding: 0%;
}
.create {
  float: right;
  margin-right: 0%;
}
.drawer_content {
  margin: 0px;
}

.text {
  font-size: 14px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
}

.el-btn {
  width: 100%;
  margin-top: 5px;
  margin-bottom: 5px;
}

.drawer-footer {
  margin-right: 30px;
  margin-left: 30px;
}
.ptree {
  margin-bottom: 25px;
  margin-top: 15px;
  max-height: 500px;
  overflow-y: auto;
}
.el-drawer.rtl {
  overflow: scroll;
}
</style>